﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Dsl.Ped.Framework.WPFControls.KeyAction
{
    /// <summary>
    /// Interaction logic for KeyActionUserControl.xaml.
    /// This control is intended to execute a specific action when a defined
    /// key is clicked.
    /// </summary>
    public partial class KeyActionUserControl : UserControl
    {
        public static readonly DependencyProperty KeyProperty;

        /// <summary>
        /// Gets or sets the key that initiates the <see cref="Action"/>
        /// </summary>
        public Key Key
        {
            get
            {
                return (Key)GetValue(KeyProperty);
            }
            set
            {
                SetValue(KeyProperty, value);
            }
        }

        /// <summary>
        /// <see cref="DependencyProperty"/> that refers to a required
        /// action to be executed
        /// </summary>
        public static readonly DependencyProperty ActionProperty;

        /// <summary>
        /// <see cref="Action"/> to be executed when the defined <see cref="Key"/>
        /// is pressed.
        /// </summary>
        public Action Action
        {
            get
            {
                return (Action)GetValue(ActionProperty);
            }
            set
            {
                SetValue(ActionProperty, value);
            }
        }

        /// <summary>
        /// Static constructor
        /// </summary>
        static KeyActionUserControl()
        {
            KeyProperty = DependencyProperty.Register(
                "Key", typeof(Key), typeof(KeyActionUserControl));

            ActionProperty = DependencyProperty.Register(
                "Action", typeof(Action), typeof(KeyActionUserControl));
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="KeyActionUserControl"/> class.
        /// </summary>
        public KeyActionUserControl()
        {
            InitializeComponent();

            textBox.PreviewKeyDown += new KeyEventHandler(onPreviewKeyDown);
        }

        private void onPreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key)
            {
                if (Action != null)
                {
                    Action.Invoke();
                }
            }

            if (e.Key != Key.Tab)
            {
                e.Handled = true;
            }
        }
    }
}
